package com.foryou.wechat.config;

import com.alibaba.fastjson.JSONObject;
import com.foryou.wechat.entity.SysUserTokenEntity;
import com.foryou.wechat.service.UserTokensService;
import com.foryou.wechat.utils.HttpContextUtils;
import com.foryou.wechat.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Lee.
 */
@Component
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    private final UserTokensService userTokensService;

    public LogInterceptor(UserTokensService userTokensService) {
        this.userTokensService = userTokensService;
    }

    //业务处理器处理请求之前被调用，对用户的request进行处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info("【拦截器】-【已进入拦截器！！】");
        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            String jsonObjectStr = JSONObject.toJSONString(Response.failure(403, "对不起，请先登录"));
            returnJson(response, jsonObjectStr);
            return false;
        }
        if (request.getRequestURI().indexOf("/getFor") > -1 || request.getRequestURI().indexOf("/pushUser") > -1) {
            SysUserTokenEntity tokenEntity = userTokensService.queryByToken(token);
            //token失效
            if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
                String jsonObjectStr = JSONObject.toJSONString(Response.failure(403, "对不起，请先登录"));
                returnJson(response, jsonObjectStr);
                return false;
            }
        }else {
            Long userId = userTokensService.getUserId(token);
            if (null == userId) {
                String jsonObjectStr = JSONObject.toJSONString(Response.failure(403, "对不起，无效的TOKEN"));
                returnJson(response, jsonObjectStr);
                return false;
            }
            HttpContextUtils.setUserId(userId);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            log.error("response error",e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}